package com.sys.server.modules.service;

import com.sys.server.common.constants.CommonConstant;
import com.sys.server.common.utils.HttpServletUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * token相关操作
 *
 * @author shanbingzhen
 * @date 2022-01-10 20:59
 */
@Service
public class TokenService {

    private static final Logger LOG = LoggerFactory.getLogger(TokenService.class);

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 生成token
     *
     * @return token
     */
    public String createToken() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().replace("-", "");
    }

    /**
     * 通过token获取当前用户的uid
     *
     * @return 当前用户uid
     */
    public String getCurrentUser() {
        String token = HttpServletUtil.getRequestHeader(CommonConstant.Authentication);
        String uid = "";
        if (token != null && Boolean.TRUE.equals(redisTemplate.hasKey(token))) {
            uid = redisTemplate.opsForValue().get(token);
        }
        if (StringUtils.isNotBlank(uid)) {
            return uid;
        } else {
            LOG.error("=====获取当前用户失败=====");
            return null;
        }
    }


    /**
     * 根据token获取当前用户
     *
     * @param token
     * @return
     */
    public String getUserBytoken(String token) {
        String uid = "";
        if (Boolean.TRUE.equals(redisTemplate.hasKey(token))) {
            uid = redisTemplate.opsForValue().get(token);
        }
        if (StringUtils.isNotBlank(uid)) {
            return uid;
        } else {
            LOG.error("=====获取当前用户失败=====");
            return null;
        }
    }

}
